<template>
  <div class="quote-price-wrapper">
    <transition-group name="slide-fade">
      <a-card :bordered="false" :key="1" title="客户资料">
        <a-descriptions margin="0 2px" :column="5">
          <a-descriptions-item label="客户姓名">
            {{ amt ? amt.name : '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="客户卡号">
            {{ amt ? amt.cardNo : '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="增值金">
            {{ amt ? amt.valueGold : '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="积分剩余">
            {{ amt ? amt.usedIntegral : '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="消费券剩余">
            {{ amt ? amt.usableTicketAmt : '-' }}
          </a-descriptions-item>
        </a-descriptions>
        <a-row style="height: 50px;">
          <a-col :span="7">
            <a-form :form="form" layout="inline" :selfUpdate="true">
              <a-form-item label="选择主诉" has-feedback>
                <a-select
                  @change="changeMainItem"
                  allow-clear
                  :showSearch="true"
                  option-filter-prop="children"
                  style="width: 160px;"
                  placeholder="选择主诉,可搜索"
                  v-decorator="['quoteItemList', {rules: [{ required: true, message: '请选择主诉！' }]}]"
                  option-label-prop="label"
                >
                  <a-select-option v-for="item in ConsultationAppeal" :key="item.id" :label="item.name"
                                   :value="item.id">{{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :span="16" style="overflow-y: auto;height: 100%">
            <a-form :form="form" layout="inline">
              <a-form-item label="历史诉求">
                <span v-if="historyItem.length<=0">无</span>
                <span v-else>
                  <a-radio-group v-model="history_item_value" @change="onChangeRadio">
                    <a-radio-button
                      v-for="item in historyItem"
                      :key="item.id"
                      :value="item.id"
                      style="margin-right: 15px;margin-bottom: 10px;">
                      {{ item.name }}
                    </a-radio-button>
                  </a-radio-group>
                </span>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
      </a-card>
      <a-card :key="2" :bordered="false" title="客户开单列表">
        <a-button type="primary" icon="plus-circle" style="margin-bottom: 15px;" @click="$refs.itemSelectDrawer.show()">
          新增项目
        </a-button>
        <a-form :form="form" layout="inline" :selfUpdate="true">
          <a-table
            size="small"
            :scroll="{x:800}"
            class="table"
            :columns="tableColumns"
            :data-source="tableData"
            :pagination="false"
            :rowKey="(record,index)=>rowKey(record,index)">

            <!--序号-->
            <template slot="index" slot-scope="text,record,index">
              <span v-if="!disabledSubmit(record)">{{ index + 1 }}</span>
            </template>

            <!--是否提交-->
            <template slot="isSubmit" slot-scope="text,record,index">
              <a-checkbox v-if="!disabledSubmit(record)" :checked="checkedNumToBool(record.isSubmit)"
                          @change="e => checkChange(e,index, 'isSubmit')"/>
            </template>
            <!--项目-->
            <template slot="itemName" slot-scope="text,record">
              <a-tooltip>
                <template slot="title">{{ text }}</template>
                <span style="font-size: 12px;" v-if="disabledSubmit(record)">  {{ text }}</span>
                <span v-else style="font-weight:bold;font-size: 13px;"> {{ text }}</span>
              </a-tooltip>
            </template>
            <!--类型-->
            <template slot="type" slot-scope="record">
              <span style="color: #3399FF" v-if="itemType(record)==1"><a-badge color="#3399FF"/>项目</span>
              <span style="color: #5AC4C2" v-if="itemType(record)==2"><a-badge color="#5AC4C2"/>产品</span>
              <span style="color: #FC9C17" v-if="itemType(record)==3"><a-badge color="#FC9C17"/>活动</span>
              <span style="color: #FF1F1F" v-if="itemType(record)==4"><a-badge color="#FF1F1F"/>套餐</span>
            </template>
            <!--科室-->
            <template slot="execDept" slot-scope="text">
              <a-tooltip>
                <template slot="title">
                  {{ text }}
                </template>
                {{ text }}
              </a-tooltip>
            </template>
            <!--价格-->
            <template slot="itemPrice" slot-scope="text,record">
              <a-form-item>
                <span >{{ text }}</span>
<!--                <a-input-->
<!--                  v-else-->
<!--                  type="number"-->
<!--                  v-decorator="[`price${record.index}`,{initialValue:text,rules: [{ required: true, message: '必填！' },{validator: validatorPrice}]}]"-->
<!--                  @change="e => handleChangeNumber(e.target.value, record, 'itemPrice')"/>-->
              </a-form-item>
            </template>
            <!--单位-->
            <template slot="itemUnit" slot-scope="text, record">
              <a-input :value="text" @change="e => handleChange(e.target.value, record.itemId, 'itemUnit')"/>
            </template>
            <!--数量-->
            <template slot="qty" slot-scope="text">
              <a-form-item>
                <span>{{ text }}</span>
<!--                <a-input-->
<!--                  v-else-->
<!--                  type="number"-->
<!--                  v-decorator="[`qty${record.index}`,{initialValue:text,rules: [{validator: validatorQty}]}]"-->
<!--                  @change="e => handleChangeQty(e.target.value, record.itemId, 'qty',index)"/>-->
              </a-form-item>
            </template>
            <!--折扣率-->
            <template slot="discount" slot-scope="text, record">
              <a-form-item  >
                <span v-if="disabledPackage(record)">{{ text }}</span>
                <a-input-number
                  v-else
                  style="width:80px; "
                  v-decorator="[`discount${record.index}`,{initialValue:record.discount,rules: [{validator: validatorDiscount}]}]"
                  :min="0"
                  :max="100"
                  :formatter="value => `${value}%`"
                  :parser="value => value.replace('%', '')"
                  @change="e => handleChange(e, record.itemId, 'discount')"
                />
              </a-form-item >
            </template>
            <!--折扣说明-->
            <template slot="discountRemark" slot-scope="text, record">

              <a-input :disabled="disabledDeduct(record)" :value="text" @change="e => handleChange(e.target.value, record.itemId, 'discountRemark')"/>
            </template>
            <!--增值金抵扣-->
            <template slot="itemTicket" slot-scope="text, record">
              <a-form-item  >
                <a-input
                  style="font-size: 13px;padding-left:4px;"
                  v-if="disabledDeduct(record)"
                  :disabled="disabledDeduct(record)"
                  :value="'总计：'+totalItemTicket(record)"
                  @change="e => handleChangeNumber(e.target.value, record, 'itemTicket')"/>
                <a-input
                  v-else
                  type="number"
                  v-decorator="[`itemTicket${record.index}`,{initialValue:text,rules: [{ required: true, message: '必填！' },{validator:(r,v,c)=> validatorDeduct(r,v,c,record,'itemTicket')}]}]"
                  @change="e => handleChangeNumber(e.target.value, record, 'itemTicket')"/>
              </a-form-item>
            </template>

            <!--券抵扣-->
            <template slot="itemGold" slot-scope="text, record">
              <a-form-item>
                <a-input
                  style="font-size: 13px;padding-left:4px;"
                  v-if="disabledDeduct(record)"
                  :disabled="disabledDeduct(record)"
                  :value="'总计：'+totalItemGold(record)"
                  @change="e => handleChangeNumber(e.target.value, record, 'itemGold')"/>
                <a-input
                  v-else
                  type="number"
                  :disabled="disabledDeduct(record)"
                  v-decorator="[`itemGold${record.index}`,{initialValue:text,rules: [{ required: true, message: '必填！' },{validator:(r,v,c)=> validatorDeduct(r,v,c,record,'itemGold')}]}]"
                  @change="e => handleChangeNumber(e.target.value, record, 'itemGold')"/>
              </a-form-item>
            </template>

            <!--积分抵扣-->
            <template slot="itemJf" slot-scope="text, record">
              <a-form-item>
                <a-input
                  style="font-size: 13px;padding-left:4px;"
                  v-if="disabledDeduct(record)"
                  :disabled="disabledDeduct(record)"
                  :value="'总计：'+totalItemJf(record)"
                  @change="e => handleChangeNumber(e.target.value, record, 'itemJf')"/>
                <a-input
                  v-else
                  type="number"
                  v-decorator="[`itemJf${record.index}`,{initialValue:text,rules: [{ required: true, message: '必填！' },{validator:(r,v,c)=> validatorDeduct(r,v,c,record,'itemJf')}]}]"
                  :disabled="disabledDeduct(record)"
                  @change="e => handleChangeNumber(e.target.value, record, 'itemJf')"/>
              </a-form-item>
            </template>

            <!--备注-->
            <template slot="remark" slot-scope="text, record">
              <a-input :disabled="disabledDeduct(record)" :value="text" @change="e => handleChange(e.target.value, record.itemId, 'remark')"/>
            </template>

            <!--成交金额-->
            <template slot="chargeAmt" slot-scope="record">
              <span v-if="disabledDeduct(record)">{{ totalChargeAmt(record) }}</span>
              <span v-else>{{ chargeAmt(record) }}</span>
            </template>
            <!--应付金额-->
            <template slot="payableAmt" slot-scope="record">
              <span v-if="disabledDeduct(record)">{{ totalPayableAmt(record) }}</span>
              <span v-else>{{ payableAmt(record) }}</span>
            </template>
            <!--操作-->
            <template slot="operation" slot-scope="text,record,index">
              <div class="editable-row-operations">
                <a @click="() => deleteFromTable(record,index)">删除</a>
              </div>
            </template>
          </a-table>
        </a-form>

      </a-card>
      <div style="margin: 20px;padding-bottom: 20px;" :key="3">
        <a-button type="primary" style="margin-right: 20px;" @click="submitForm" :loading="confirmLoading">确定</a-button>
        <a-button @click="goBack">返回</a-button>
      </div>
    </transition-group>
    <item-select-drawer :tableData="tableData" @dbclick_row="dbclick_row" ref="itemSelectDrawer"/>
  </div>
</template>

<script>

function initTableIndex(data, parentIndex = '') {
  for (let i = 0; i < data.length; i++) {
    data[i] = Object.assign(data[i], { index: (parentIndex === '' ? '' : parentIndex) + (parentIndex ? '-' : '') + i })
    if (data[i].children) {
      initTableIndex(data[i].children, data[i].index)
    }
  }

  return data
}

import { drawBill, getQuotePrice } from '@/api/modular/main/customer/customerScene'
import { getConsultationAppeal } from '@/api/modular/main/customer/customerConsultation'
import itemSelectDrawer from '@/views/customer/customerSceneConsultation/itemSelectDrawer'

export default {
  name: 'quotePrice',
  components: {
    itemSelectDrawer
  },
  props: {
    row_record: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      confirmLoading: false,
      amt: {},
      itemAndPrice: {
        amt: {},
        MainlyItem: [],
      },
      historyItem: [],
      //客户诉求列表
      ConsultationAppeal: [],
      form: this.$form.createForm(this),
      history_item_value: '',//历史诉求
      customerDetailsForm: {},
      tableData: [],
      originTableData: [],
      visible: false,
      tableColumns: [
        { title: '序号', scopedSlots: { customRender: 'index' }, width: 70 },
        { title: '是否提交', scopedSlots: { customRender: 'isSubmit' }, width: 80 },
        { title: '项目', dataIndex: 'itemName', scopedSlots: { customRender: 'itemName' }, width: 140, ellipsis: true },
        { title: '类型', scopedSlots: { customRender: 'type' }, width: 80, ellipsis: true },
        { title: '科室', dataIndex: 'execDept', scopedSlots: { customRender: 'execDept' }, width: 100, ellipsis: true },
        { title: '价格', dataIndex: 'itemPrice', scopedSlots: { customRender: 'itemPrice' }, width: 120 },
        { title: '单位', dataIndex: 'unit', scopedSlots: { customRender: 'unit' }, width: 70 },
        { title: '数量', dataIndex: 'qty', scopedSlots: { customRender: 'qty' }, width: 120 },
        { title: '折扣率', dataIndex: 'discount', width: 90, scopedSlots: { customRender: 'discount' } },
        { title: '成交金额', width: 100, scopedSlots: { customRender: 'chargeAmt' } },
        { title: '应付金额', width: 100, scopedSlots: { customRender: 'payableAmt' } },
        { title: '折扣说明', dataIndex: 'discountRemark', width: 100, scopedSlots: { customRender: 'discountRemark' } },
        { title: '增值金抵扣', dataIndex: 'itemTicket', scopedSlots: { customRender: 'itemTicket' }, width: 125 },
        { title: '券抵扣', dataIndex: 'itemGold', scopedSlots: { customRender: 'itemGold' }, width: 125 },
        { title: '积分抵扣', dataIndex: 'itemJf', scopedSlots: { customRender: 'itemJf' }, width: 125 },
        { title: '备注', dataIndex: 'remark', width: 110, scopedSlots: { customRender: 'remark' }, ellipsis: true },
        { title: '操作', dataIndex: 'operation', scopedSlots: { customRender: 'operation' }, width: 80}
      ]
    }
  },
  methods: {
    rowKey(record, index) {
      if (record.activityId) {
        return record.itemId + index + record.activityId
      }
      if (record, index) {
        return record.itemId + index + record.memuId + index
      }
      return record.itemId + index
    },
    show() {
      this.visible = true
      this.$nextTick(() => {
        console.log('行数据', this.row_record)
        const params = {
          triageId: this.row_record.triageId,
          customerId: this.row_record.customerId
        }
        getConsultationAppeal().then(res => {
          this.ConsultationAppeal = res.data
          const schemeId = this.row_record.tbConsultSchemeId
          const customerId = this.row_record.customerId
          const triageId = this.row_record.triageId
          getQuotePrice({ schemeId, customerId, triageId }).then(res => {
            console.log('查询项目报价', res)
            this.historyItem=res.data.historyItem
            const quoteItemList = res.data.MainlyItem[0]
            if (quoteItemList ) {
              this.form.setFieldsValue({
                quoteItemList: quoteItemList.id
              })
            }
            this.amt = res.data.amt
            this.originTableData = res.data.consultItem
            const newTable = JSON.parse(JSON.stringify(this.originTableData))
            this.tableData = initTableIndex(newTable, '')
          })
        })

      })
    },
    dbclick_row(arr) {
      // this.tableData=this.tableData.concat(arr)
      this.originTableData = this.originTableData.concat(arr)
      const newTable = JSON.parse(JSON.stringify(this.originTableData))
      this.tableData = initTableIndex(newTable, '')
      // console.log('888', this.tableData)
    },
    disabledSubmit(record) {
      if (record.activityId && !record.children) return true
      if (record.memuId && !record.children) return true
      return false
    },
    disabledPackage(record) {
      if (record.activityId || record.memuId) return true
      return false
    },
    disabledDeduct(record) {
      if (record.activityId && record.children) return true
      if (record.memuId && record.children) return true
      return false
    },
    //数字与布尔类型互相转换
    checkedNumToBool(isSubmit) {
      // console.log('数字与布尔类型',typeof isSubmit)
      return typeof isSubmit === 'boolean' ? isSubmit : (isSubmit === 1 ? true : false)
    },
    /**
     表单校验
     * */
    validatorDeduct(rule, value, callback,record,column) {
      if (value < 0) {
        callback('必须为正数')
      }
      let sum =0
      if(column==='itemTicket'){
         sum =parseFloat(value)+parseFloat(record.itemGold)+parseFloat(record.itemJf)
      }
      if(column==='itemGold'){
        sum =parseFloat(value)+parseFloat(record.itemTicket)+parseFloat(record.itemJf)
      }
      if(column==='itemJf'){
        sum = parseFloat(value)+parseFloat(record.itemTicket)+parseFloat(record.itemGold)
      }
      if (sum > parseFloat(this.payableAmt(record))) {
        callback('不能大于应付金额')
      }
      callback()
    },
    /**
     表单校验-价格
     * */
    validatorPrice(rule, value, callback) {
      if(value.length >1 && value.substring(0,1)=='0'){
        callback('不能以0开头')
      }
      if (value <0) {
        callback('必须为非负数')
      }
      callback()
    },
    /**
     表单校验-数量
     * */
    validatorQty(rule, value, callback) {
      if (value >= 1) {
        callback()
      }
      callback('必须为正整数')
    },
    /**
     表单校验-折扣率
     * */
    validatorDiscount(rule, value, callback) {
      if (value >= 1&&value<=100) {
        callback()
      }
      callback('必须在1到100之间')
    },
    checkChange(e, index, column) {
      const value = e.target.checked
      const newData = [...this.tableData]
      const target = this.tableData[index]

      if (target) {
        if (target.activityId) {
          this.tableData = newData.map(item => {
            if (item.activityId === target.activityId) {
              item.isSubmit = value
              //树形结构
              item.children.forEach(i => {
                i.isSubmit = value
              })
            }
            return item
          })
          return
        }
        if (target.memuId) {
          this.tableData = newData.map(item => {
            if (item.memuId === target.memuId) {
              item.isSubmit = value
              //树形结构
              item.children.forEach(i => {
                i.isSubmit = value
              })
            }
            return item
          })
          return
        }
        target[column] = value
        this.tableData = newData
      }
    },
    totalItemTicket(record){
      let sum = 0
      record.children.forEach(item => {
        sum += parseFloat(item.itemTicket)
      })
      return sum
    },
    totalItemGold(record){
      let sum = 0
      record.children.forEach(item => {
        sum += parseFloat(item.itemGold)
      })
      return sum
    },
    totalItemJf(record){
      let sum = 0
      record.children.forEach(item => {
        sum += parseFloat(item.itemJf)
      })
      return sum
    },
    totalChargeAmt(record) {
      let sum = 0
      record.children.forEach(item => {
        sum += parseFloat(this.chargeAmt(item))
      })
      return sum
    },
    totalPayableAmt(record) {
      let sum = 0
      record.children.forEach(item => {
        sum += parseFloat(this.payableAmt(item))
      })
      return sum
    },
    /**
     成交金额
     * */
    chargeAmt(record) {
      const num = parseInt(record.qty)
      const discount = parseFloat(record.discount * 0.01)
      const price = parseFloat(record.itemPrice) || 0
      const itemTicket = parseFloat(record.itemTicket) || 0
      const itemGold = parseFloat(record.itemGold) || 0
      const itemJf = parseFloat(record.itemJf) || 0
      const result = parseFloat(price * num * discount - itemTicket - itemGold - itemJf).toFixed(2)
      return result
    },
    /**
     应付金额
     * */
    payableAmt(record) {
      const num = parseInt(record.qty)
      const price = parseFloat(record.itemPrice)
      const discount = parseFloat(record.discount * 0.01)
      const result = parseFloat(price * num * discount).toFixed(2)
      return result
    },
    changeMainItem(value) {
      if (value === undefined||value!=this.history_item_value) {
        this.history_item_value = ''
      }
    },
    itemType(record) {
      if (record.activityId) return 3
      if (record.memuId) return 4
      if (record.itemType == 1) return 1
      if (record.itemType == 2) return 2

    },
    handleChange(value, itemId, column) {
      const newData = [...this.tableData]
      const target = newData.filter(item => itemId === item.itemId)[0]
      if (target) {
        target[column] = value
        this.tableData = newData
      }
    },
    isTree(index) {
      if (index.indexOf('-') > -1) return true
      return false
    },
    handleChangeNumber(value, record, column) {
      const parent_child_index = record.index
      if (this.isTree(parent_child_index)) {
        const str_index = parent_child_index.indexOf('-')
        const parent = parent_child_index.slice(0, str_index)
        const child = parent_child_index.slice(str_index + 1)
        this.tableData[parent].children[child][column] = value
      } else {
        this.tableData[parent_child_index][column] = value
      }
    },
    handleChangeQty(value, itemId, column) {
      const newData = [...this.tableData]
      const target = newData.filter(item => itemId === item.itemId)[0]
      if (target) {
        target[column] = value
        this.tableData = newData
      }
    },
    /**
     单选框
     * */
    onChangeRadio(e) {
      const id = e.target.value
      this.form.setFieldsValue({
        quoteItemList: id
      })
    },
    goBack() {
      this.$emit('goBack', false)
    },
    /**
     删除表格数据
     * */
    deleteFromTable(record, index) {
      //为活动
      console.log('record.activityId', record.activityId)
      if (record.activityId) {
        const newData = this.tableData.filter(item => item.activityId !== record.activityId)
        this.tableData = newData
        this.originTableData = newData
        return
      }
      if (record.memuId) {
        const newData = this.tableData.filter(item => item.memuId !== record.memuId)
        this.tableData = newData
        this.originTableData = newData
        return
      }
      this.tableData.splice(index, 1)
      this.originTableData.splice(index, 1)

    },
    /**
     提交表单
     * */
    submitForm() {
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (errors) {
          console.log('表单检验未通过')
          this.confirmLoading = false
          return
        }
        if (this.tableData.length <= 0) {
          this.$message.info('请选择项目')
          this.confirmLoading = false
          return
        }
        // const consultItemList=JSON.parse(JSON.stringify(this.tableData))
        var newData = []
        console.log('原内容：', this.tableData)
        this.tableData.forEach(item => {
          if (item.children) {
            newData = newData.concat(item.children)
          } else {
            newData.push(item)
          }
        })
        // console.log('新内容：', newData)
        const consultItemList = newData.map(item => {
          return {
            ...item,
            payableAmt: this.payableAmt(item),
            chargeAmt: this.chargeAmt(item),
            isSubmit: typeof (item.isSubmit) === 'number' ? item.isSubmit : (item.isSubmit === true ? 1 : 0)
          }
        })

        const params = {
          consultItemList: consultItemList,
          consultRecordId: this.row_record.consultRecordId,
          customerId: this.row_record.customerId,
          receiveItemId: this.row_record.receiveItemId,
          receiveId: this.row_record.receiveId,
          triageId: this.row_record.triageId,
          SchemeContent: this.row_record.SchemeContent, //方案内容
          appealItemList: [values.quoteItemList],
          schemeId: this.row_record.tbConsultSchemeId
        }
        console.log('8977999999',params)
        drawBill(params).then(res => {
          console.log('开单提交结果：', res)
          if (res.code == 200) {
            this.$message.success('开单成功')
            this.$emit('openBillSuccess')
            this.visible = false
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      })
    }

  }
}
</script>

<style scoped>
.slide-fade-enter-active {
  transition: all .3s ease;
}

.slide-fade-leave-active {
  transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}

.slide-fade-enter, .slide-fade-leave-to
  /* .slide-fade-leave-active for below version 2.1.8 */
{
  transform: translateX(10px);
  opacity: 0;
}

.quote-price-wrapper {
  background: #ffffff;
  width: 100%;
  height: 100%;
  z-index: 1000;
}

.footer {
  position: fixed;
  left: 240px;
  right: 20px;
  bottom: 0;
  background: #ffffff;
  height: 80px;
  z-index: 999;
}

/*/deep/ .table  .ant-input {*/
/*  border: none;*/
/*  padding: 2px 0 2px 5px;*/
/*}*/
/deep/ .ant-form-item{
  margin-bottom: 0 ;
}
</style>